import 'package:flutter/material.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../../manger/user_manger.dart';
import '../../models/home_init_model.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'dart:convert';

class CurrencySelectWidget extends StatefulWidget {
  final List<CurrencyListModel> currencyList;
  final ValueChanged<CurrencyListModel> onSelect;
  final double top;

  const CurrencySelectWidget({
    super.key,
    required this.currencyList,
    required this.onSelect,
    this.top = 100,
  });

  @override
  _CurrencySelectWidgetState createState() => _CurrencySelectWidgetState();
}

class _CurrencySelectWidgetState extends State<CurrencySelectWidget> {
  int? selectedIndex;

  @override
  void initState() {
    super.initState();
    // 设置默认选中项
    final userCurrencyId = UserInfos.shared.currencyListModel?.currencyId;
    if (userCurrencyId != null) {
      selectedIndex = widget.currencyList.indexWhere(
        (currency) => currency.currencyId == userCurrencyId,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return Stack(
          children: [
            // 黑色半透明蒙层
            Positioned(
              top: widget.top,
              left: 0,
              right: 0,
              bottom: 0,
              child: GestureDetector(
                onTap: () {
                  widget.onSelect(UserInfos.shared.currencyListModel ?? widget.currencyList.first);                
                },
                child: Container(
                color: Colors.black.withValues(alpha: 0.5),
                ),
              ),
            ),
            // 内容区域
            Positioned(
              top: widget.top,
              left: 0,
              right: 0,
              child: Container(
            color: Color(0xFFE1ECFE),
            child: GridView.builder(
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                mainAxisExtent: 44,
                mainAxisSpacing: 10,
                crossAxisSpacing: 10,
              ),
              padding: EdgeInsets.all(10),
              itemCount: widget.currencyList.length,
              itemBuilder: (context, index) {
                final currency = widget.currencyList[index];
                return GestureDetector(
                  onTap: () async {
                    setState(() {
                      selectedIndex = index;
                    });
                    UserInfos.shared.currencyListModel = currency;
                    widget.onSelect(currency);
                    final storage = FlutterSecureStorage();
                    await storage.write(
                      key: 'cached_currency',
                      value: jsonEncode(currency.toJson()),
                    );
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(8),
                    ),
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            isChineseLocale() ? '${currency.name} (${currency.code})' : currency.code,
                            style: const TextStyle(
                              fontSize: 13,
                              color: Colors.black,
                            ),
                          ),
                        ),
                        Image.asset(
                          selectedIndex == index
                              ? 'assets/images/login_select.png'
                              : 'assets/images/login_unselect.png',
                          width: 20,
                          height: 20,
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
        ),
      ],
    );
  },
);  
  }
}